package com.tanhua.manager.service;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tanhua.manager.constant.CacheKey;
import com.tanhua.manager.domain.Admin;
import com.tanhua.manager.exception.BusinessException;
import com.tanhua.manager.interceptor.AdminHolder;
import com.tanhua.manager.mapper.AdminMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService  extends ServiceImpl<AdminMapper, Admin> {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Value("${tanhua.secret}")
    private String secret;
    /**
     * 把验证码真实值缓存到Redis里
     * @param code 验证码值
     * @param uuid 客户端提供的随机字符串，作为缓存验证码时的key
     */
    public void cacheCode(String code, String uuid) {
        redisTemplate.opsForValue().set(CacheKey.CODE_PREFIX +uuid,code,Duration.ofMinutes(5));
    }

    //登录
    /**
     * 登录校验
     * @param username 帐号
     * @param password 密码
     * @param code 验证码
     * @param uuid 验证码的标识符
     */
    public ResponseEntity login(String username, String password, String code, String uuid) {
        //校验验证码
        String value = redisTemplate.opsForValue().get(CacheKey.CODE_PREFIX + uuid);
        if (value==null||!value.equals(code)){
            throw new BusinessException("验证码错误");
        }
        redisTemplate.delete(CacheKey.CODE_PREFIX+uuid);

        //2. 再校验帐号和密码
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        wrapper.eq("password", SecureUtil.md5(password));
        Admin admin = adminMapper.selectOne(wrapper);
        if (admin==null){
            throw  new  BusinessException("用户名不存在");

        }
        if (password==null||!SecureUtil.md5(password).equals(admin.getPassword())){
            throw  new BusinessException("密码错误");

        }
        //生成token 缓存到redis里
        Map<String, Object> claims = new HashMap<>();
        claims.put("id",admin.getId());
        claims.put("username",admin.getUsername());
      String token= Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS256,secret)
                .compact();
        redisTemplate.opsForValue().set(CacheKey.TOKEN_PREFIX+token, JSON.toJSONString(admin),Duration.ofHours(1));
        //返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("token",token);
        return  ResponseEntity.ok(result);
    }

    //获取用户基本信息
    public ResponseEntity getAdminInfo() {
        //从Redis中获取token对应的用户信息
        Admin admin = AdminHolder.getAdmin();

        //响应给客户端（注意不要把密码响应给客户端）
        Map<String, Object> result = new HashMap<>();
          result.put("id",admin.getId().toString());
          result.put("username",admin.getUsername());
          result.put("avatar",admin.getAvatar());
          return ResponseEntity.ok(result);
    }
 //退出登录
    public ResponseEntity logout() {
        String token = AdminHolder.getToken();
        redisTemplate.delete(CacheKey.TOKEN_PREFIX+token);
        return ResponseEntity.ok(null);
    }
}
